// product.js
import { Product } from 'product-model.js'
import {Cart} from '../cart/cart-model.js'

var product = new Product
var cart = new Cart

Page({

  /**
   * 页面的初始数据
   */
  data: {
    "id": 0,
    "countsArray": [1,2,3,4,5,6,7,8,9,10],
    "productCount": 1,
    "currentTabsIndex":0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options);
    var id = options.id;
    this.data.id = id;

    this._loadData();
  },

  _loadData: function() {
    product.getProductInfo(this.data.id, (data) => {
      console.log(cart.getCartTotalCounts())
      this.setData({
        "cartTotalCounts": cart.getCartTotalCounts(),
        "product": data
      });
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  bindPickerChange: function(event) {
    var idx = event.detail.value;
    this.setData({
      "productCount": this.data.countsArray[idx]
    });
  },

  //点击商品详情导航的时候
  onTabsItemTap: function(event) {
    var idx = product.getDataset(event, 'index');
    this.setData({
      "currentTabsIndex": idx
    });
  },

  /**
   * 点击添加到购物车的时候
   */
  onAddingToCartTap: function(event) {
    this.addItemToCart();

    var totalCount = this.data.cartTotalCounts + this.data.productCount;
    this.setData({
      "cartTotalCounts": totalCount
    });
  },

  /**
   * 点击购物车图标跳转到购物车页面
   * @notice 必须是绝对路径
   */
  onCartTap: function(event) {
      wx.switchTab({
        url: '/pages/cart/cart',
      })
  },

  /**
   * 获取预先要添加到购物车的商品
   */
  addItemToCart: function() {
    var obj = {};
    var keys = ['id', 'name', 'price', 'main_img_url'];

    for(let i=0; i<keys.length; i++) {
      let attr = keys[i];
      if (this.data.product[attr]) {
        obj[attr] = this.data.product[attr];
      }
    }

    cart.addCart(obj, this.data.productCount);
  }
})